package zmee.pur.src.formplugin.filter;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2022/11/21/15:46
 * @Description:
 */
public class FilterByRule {
    /**
     * 竞争性谈判按供应商未税金额总和议价
     *
     * @return java.util.Set<java.lang.Long>
     * @Param
     * @Date 2022/12/4 10:46
     * @Author xw
     **/
    public static Set<Long> getIdsByPrice(QFilter filter, QFilter compareFilter, long projectId) {
        //之后议价轮次
        boolean flag = isFlag(filter);
        Set<Long> ids = new HashSet<Long>();
        if (flag) {
            //金额发生变更
            List<Long> resultSuppliers = new ArrayList<>();
            DynamicObject projectRule = QueryServiceHelper.queryOne("src_project_rule", "id,zmee_tpspreads", compareFilter.toArray());
            QFilter bizFilter = new QFilter("billid", "=", projectId);
            DynamicObjectCollection bidassess = QueryServiceHelper.query("src_bidassess_biz", "id,rank,locamount,supplier",
                    bizFilter.toArray());
            for (DynamicObject one : bidassess) {
                int oneRank = one.getInt("rank");
                if (oneRank != 1) {
                    continue;
                }
                for (DynamicObject obj : bidassess) {
                    int rank = obj.getInt("rank");
                    if (rank != 1) {
                        resultSuppliers.add(one.getLong("supplier"));
                        BigDecimal oneLocAmount = one.getBigDecimal("locamount");
                        BigDecimal locAmount = obj.getBigDecimal("locamount");
                        //总价差率=（总价次高价-总价最低价）/总价最低价*100%<谈判总价差（0.5%）
                        BigDecimal totalScoreDifference = (locAmount.subtract(oneLocAmount)).divide(oneLocAmount, 5,
                                RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                        if (totalScoreDifference.compareTo(projectRule.getBigDecimal("zmee_tpspreads")) < 0) {
                            resultSuppliers.add(obj.getLong("supplier"));
                        }
                    }
                }
            }
            ids = getLongs(filter, resultSuppliers);
        }
        return ids;
    }

    /**
     * 竞争性谈判按物料未税金额议价
     *
     * @return java.util.Set<java.lang.Long>
     * @Param
     * @Date 2022/12/4 10:46
     * @Author xw
     **/
    public static Set<Long> getIdsByPrice(QFilter filter, QFilter compareFilter) {
        //之后议价轮次
        //查询状态为 已开标、已关闭的报价分析
        filter.and("entrystatus", "in", new String[]{"C", "D"});
        DynamicObjectCollection purList = QueryServiceHelper.query("src_analysetool", "id,turns,rank,supplier,amount,taxamount,material",
                filter.toArray(), "turns");
        //轮次分组
        Map<Object, List<DynamicObject>> listMap = purList.stream().collect(Collectors.groupingBy(p -> p.get("turns")));
        boolean flag = false;
        int size1 = listMap.size();
        String first = String.valueOf((size1 - 1));
        String last = String.valueOf(size1);
        List<DynamicObject> firstList = listMap.get(first);
        List<DynamicObject> lastList = listMap.get(last);
        for (DynamicObject lObj : lastList) {
            for (DynamicObject fObj : firstList) {
                long fSupplier = fObj.getLong("supplier");
                long lSupplier = lObj.getLong("supplier");
                long fNumber = fObj.getLong("material");
                long lNumber = lObj.getLong("material");
                //同一个供应商两轮金额是否变更
                if (fSupplier == lSupplier && fNumber == lNumber) {
                    BigDecimal fTaxAmount = fObj.getBigDecimal("amount");
                    BigDecimal lTaxAmount = lObj.getBigDecimal("amount");
                    if (fTaxAmount.compareTo(lTaxAmount) != 0) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        Set<Long> ids = new HashSet<Long>();
        if (flag) {
            //金额发生变更
            DynamicObject projectRule = QueryServiceHelper.queryOne("src_project_rule", "id,zmee_tpspreads", compareFilter.toArray());
            for (DynamicObject one : lastList) {
                int oneRank = one.getInt("rank");
                long oneMaterial = one.getLong("material");
                if (oneRank != 1) {
                    continue;
                }
                Set<Long> tempIds = new HashSet<Long>();
                for (DynamicObject obj : lastList) {
                    int rank = obj.getInt("rank");
                    long material = obj.getLong("material");
                    if (rank != 1 && oneMaterial == material) {
                        tempIds.add(one.getLong("id"));
                        BigDecimal oneTaxAmount = one.getBigDecimal("amount");
                        BigDecimal taxAmount = obj.getBigDecimal("amount");
                        //总价差率=（总价次高价-总价最低价）/总价最低价*100%<谈判总价差（0.5%）
                        BigDecimal totalPriceDifference = (taxAmount.subtract(oneTaxAmount)).divide(oneTaxAmount, 5,
                                RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                        if (totalPriceDifference.compareTo(projectRule.getBigDecimal("zmee_tpspreads")) < 0) {
                            tempIds.add(obj.getLong("id"));
                        }
                    }
                }
                if (tempIds.size() != 1) {
                    ids.addAll(tempIds);
                }
            }
        }
        return ids;
    }

    /**
     * 竞争性磋商按供应商总得分议价
     *
     * @return java.util.Set<java.lang.Long>
     * @Param
     * @Date 2022/12/4 10:50
     * @Author xw
     **/
    public static Set<Long> getIdsByScore(QFilter filter, QFilter compareFilter, long projectId) {
        //之后议价轮次
        //查询状态为 已开标、已关闭的报价分析
        boolean flag = isFlag(filter);
        Set<Long> ids = new HashSet<Long>();
        if (flag) {
            //金额发生变更
            List<Long> resultSuppliers = new ArrayList<>();
            DynamicObject projectRule = QueryServiceHelper.queryOne("src_project_rule", "id,zmee_csscoregap", compareFilter.toArray());
            QFilter bizFilter = new QFilter("billid", "=", projectId);
            DynamicObjectCollection bidassess = QueryServiceHelper.query("src_bidassess_biz", "id,rank,sumscore,supplier",
                    bizFilter.toArray());
            for (DynamicObject one : bidassess) {
                int oneRank = one.getInt("rank");
                for (DynamicObject obj : bidassess) {
                    int rank = obj.getInt("rank");
                    if (oneRank == 1 && rank != 1) {
                        resultSuppliers.add(one.getLong("supplier"));
                        BigDecimal oneSumScore = one.getBigDecimal("sumscore");
                        BigDecimal sumScore = obj.getBigDecimal("sumscore");
                        //综合分差率=（综合分最高分-综合分次高分）/综合分最高分*100%<磋商综合分差（0.5%）
                        BigDecimal totalScoreDifference =
                                (oneSumScore.subtract(sumScore)).divide(oneSumScore, 5, RoundingMode.HALF_UP).multiply(new BigDecimal(
                                        "100"));
                        if (totalScoreDifference.compareTo(projectRule.getBigDecimal("zmee_csscoregap")) < 0) {
                            resultSuppliers.add(obj.getLong("supplier"));
                        }
                    }
                }
            }

            ids = getLongs(filter, resultSuppliers);
        }
        return ids;
    }

    private static boolean isFlag(QFilter filter) {
        //查询状态为 已开标、已关闭的报价分析
        filter.and("entrystatus", "in", new String[]{"C", "D"});
        DynamicObjectCollection purList = QueryServiceHelper.query("src_analysetool", "id,turns,rank,supplier,amount,taxamount,material",
                filter.toArray(), "turns");
        //轮次分组
        Map<Object, List<DynamicObject>> listMap = purList.stream().collect(Collectors.groupingBy(p -> p.get("turns")));
        boolean flag = false;
        int size1 = listMap.size();
        String first = String.valueOf((size1 - 1));
        String last = String.valueOf(size1);
        List<DynamicObject> firstList = listMap.get(first);
        List<DynamicObject> lastList = listMap.get(last);
        for (DynamicObject lObj : lastList) {
            for (DynamicObject fObj : firstList) {
                long fSupplier = fObj.getLong("supplier");
                long lSupplier = lObj.getLong("supplier");
                long fNumber = fObj.getLong("material");
                long lNumber = lObj.getLong("material");
                //同一个供应商两轮金额是否变更
                if (fSupplier == lSupplier && fNumber == lNumber) {
                    BigDecimal fTaxAmount = fObj.getBigDecimal("amount");
                    BigDecimal lTaxAmount = lObj.getBigDecimal("amount");
                    if (fTaxAmount.compareTo(lTaxAmount) != 0) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    private static Set<Long> getLongs(QFilter filter, List<Long> resultSuppliers) {
        Set<Long> ids;
        filter.and("entrystatus", "=", "C").and("supplier.id", "in", resultSuppliers);
        DynamicObjectCollection analyseTools = QueryServiceHelper.query("src_analysetool", "id,turns", filter.toArray(), "turns");
        if (analyseTools.isEmpty()) {
            return null;
        }
        //轮次分组
        Map<Object, List<DynamicObject>> listMap = analyseTools.stream().collect(Collectors.groupingBy(p -> p.get("turns")));
        List<DynamicObject> dynamicObjects = analyseTools;
        if (listMap.size() > 1) {
            String turns = analyseTools.get(analyseTools.size() - 1).getString("turns");
            dynamicObjects = listMap.get(turns);
        }
        ids = dynamicObjects.stream().map(a -> a.getLong("id")).collect(Collectors.toSet());
        return ids;
    }
}
